import Singleton from "../Base/Singleton";
import { ItemStatusEnum, ItemTypeEnum } from "../Enum";

interface IItem{
    func: Function,
    ctx: unknown,
}

export default class EventManger extends Singleton{
    static get Instance() {
        return super.getInstance<EventManger>()

    }

    private eventDic: Map<string, Array<IItem>> = new Map()
    
    on(eventname: string, func: Function, ctx?: unknown) {
        if (this.eventDic.has(eventname)) {
            this.eventDic.get(eventname).push({func,ctx})

        } else {
            this.eventDic.set(eventname, [{func,ctx}])
        }
    }

    off(eventname: string, func: Function,ctx?: unknown) {
        if (this.eventDic.has(eventname)) {
            const index = this.eventDic.get(eventname).findIndex(i => i.func === func && i.ctx === ctx)
            index > -1 && this.eventDic.get(eventname).splice(index, 1)
        }
    }

    clear() {
        this.eventDic.clear()
    }

    emit(eventname: string,...parms:unknown[]) {
        if (this.eventDic.has(eventname)) {
            this.eventDic.get(eventname).forEach(({ func, ctx }) => {
                ctx?func.apply(ctx):func(...parms)  
            })
        }
    }

}


